package com.springboot.mybatis.adapter;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.springboot.mybatis.interceptor.BackInterceptor;
import com.springboot.mybatis.interceptor.FrontInterceptor;

@Configuration
public class ConfigAdapter implements WebMvcConfigurer{
    
    private static final Logger log = LoggerFactory.getLogger(ConfigAdapter.class);  
     
    @Resource
    BackInterceptor backInterceptor;
    @Resource
    FrontInterceptor frontInterceptor;
    
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("forward:/admin/login");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
    }
    
    @Override
    public void addInterceptors(InterceptorRegistry registry){
        log.info("*********addInterceptors*********");
        registry.addInterceptor(backInterceptor)
                .addPathPatterns("/admin/**")
                .excludePathPatterns("/admin/login", "/admin/logout");
        registry.addInterceptor(frontInterceptor).addPathPatterns("/front/**");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry){
        log.info("*********addResourceHandlers*********");
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        log.info("*********addCorsMappings*********");
        registry.addMapping("/**")//设置允许跨域的路径
                .allowedOrigins("*")//设置允许跨域请求的域名
                .allowCredentials(true)//是否允许证书 不再默认开启
                .allowedMethods("GET", "POST", "PUT", "DELETE")//设置允许的方法
                .allowedHeaders("*")
                .maxAge(3600);//跨域允许时间
    }
}
